<template>
    <div class="search-view">
        <div class="search-top" :class="{resultbg: showSearchResult}">
            <img src="../assets/images/sreach/left.png" @click="returnInput">
            <div class="search-input">
                <input type="text" placeholder="搜索商品名称" v-model="values" @input="getSuggestList" @focus="searchFocusHandle" @keyup.enter="searchKeyWord(values)">
            </div>
            <img src="../assets/images/sreach.png" alt="" @click="searchKeyWord(values)">
        </div>

        <div class="search-first" v-show="!showSearchResult && !showSuggest">
            <!-- 搜索历史 -->
            <div class="search-history" v-show="searchHistory[0]">
                <div class="search-title">
                    <div>搜索历史</div>
                    <img src="../assets/images/sreach/del.png" @click="removeSearchHistory">
                </div>
                <div class="search-history-list">
                    <a class="search-history-item" v-for="(l, index) in searchHistory" :key="index" @click="searchKeyWord(l)">{{l}}</a>
                </div>
            </div>
        
            <!-- 搜索发现 -->
            <div class="search-discover">
                <div class="search-title">搜索发现</div>
                <div class="search-discover-list">
                    <div class="search-discover-item" v-for="d in discoverList" :key="d.id" @click="searchKeyWord(d.desc)">{{d.desc}}</div>
                </div>
            </div>
        </div>

        <!-- 搜索建议 -->
        <div class="search-suggest" v-show="showSuggest">
            <div class="search-suggest-item" v-for="(s, index) in suggestList" :key="index" @click="searchKeyWord(s.title)">{{s.title}}</div>
        </div>

        <!-- 搜索结果 -->
        <div class="search-result" v-show="showSearchResult">
            <!-- 搜索结果 nav -->
            <div class="search-result-nav">
                <div class="search-result-nav-item" :class="{active: resultActive === 0}" @click="toggleResultNav(0)">{{ showRankTxt }}
                    <i class="icon-down1"></i>
                </div>

                <div class="search-result-nav-item" :class="{active: resultActive === 1}" @click="toggleResultNav(1)">销量</div>
                <div class="search-result-nav-item" :class="{active: resultActive === 2}" @click="toggleResultNav(2)">价格
                    <i class="icon-up" :class="{active: resultActive === 2 & priceOrder == 'asc'}"></i>
                    <i class="icon-down" :class="{active: resultActive === 2 & priceOrder == 'dsc'}"></i>
                </div>
                <div class="search-result-nav-item" @click="showFilter = true">筛选</div>
            </div>

            <!-- 综合弹窗 -->
            <div class="search-result-nav1" v-show="showRank">
                <div class="search-result-nav1-item" v-for="(r, i) in rankList" :key="i" :class="{active: rank === i}" @click="toggleShowRank(i)">{{ r }}</div>
                <div class="fill-content" @click="showRank = false"></div>
            </div>

            <!-- 筛选弹窗 -->
            <van-popup v-model="showFilter" position="right" :style="{ width: '85%', height: '100%' }">
                <div class="popup-list-box">
                    <div class="popup-list">
                        <div class="popup-item">
                            <div class="popup-item-title mt-4">
                                <div>服务</div>
                                <div class="span-location" v-show="!$store.state.local" @click="showArea"><img src="../assets/images/sreach/location.png">选择配送地址</div>
                                <div class="span-location"  v-show="$store.state.local" @click="showArea"><img src="../assets/images/sreach/location.png">{{ $store.state.local }}</div>
                                <van-action-sheet v-model="showarea" position="right" style="width: 100%; height: 100%;">
                                        <div class="content"> <van-area title="地址" :area-list="areaList" @confirm="changeValue" :value='`${cityvalue}`' /></div>
                                                </van-action-sheet>                        
                            </div>
                            <div class="popup-item-con">
                                <div :class="{active: s.checked}" v-for="(s,i) in resultList.filter_tags" :key="s.value" @click="toggleFilter(resultList.filter_tags, i)">{{ s.name }}</div>
                            </div>
                        </div>

                        <div class="popup-item">
                            <div class="popup-item-title">
                                <div>分类</div>
                                <div v-show="resultList.classes?.length > 3" :class="showShorter?'span-down':'span-up'" @click="shorter"></div>
                            </div>
                            <div class="popup-item-con" :class="{active: showShorter}">
                                <div :class="{active: tab.checked}" v-for="(tab, i) in resultList.classes" :key="i" @click="toggleFilterTab(resultList.classes, i)">{{ tab.class_name }}</div>
                            </div>
                        </div>

                        <!-- 点击后添加的 -->
                        <div class="popup-item" v-for="(c,i) in resultList.classes?resultList.classes[classesNum]?.class_parameters:''" :key="i" v-show="showParameters">
                            <div class="popup-item-title">
                                <div>{{ c.parameter_name }}</div>
                                <div v-show="c.rules.length > 3" :class="showShorter?'span-down':'span-up'" @click="shorter"></div>
                            </div>
                            <div class="popup-item-con" :class="{active: showShorter}">
                                <div :class="{active: cList.checked}" v-for="(cList, index) in c.rules" :key="index" @click="toggleFilter(resultList.classes[classesNum]?.class_parameters[i].rules, index)">{{ cList.name }}</div>
                            </div>
                        </div>
                    </div>
                    <!-- 提交按钮 -->
                    <div class="submit-btn">
                        <button @click="resetBtn">重置</button>
                        <button @click="submitBtn">确定</button>
                    </div>
                </div>
            </van-popup>
            

            <!-- 请求未完成时 -->
            <div class="requesting" v-if="!requestSuccess">
                <img src="../assets/images/sreach/loading.gif" alt="">
                <div>数据请求中</div>
            </div>
            
            <!-- 请求完成时 -->
            <div v-if="requestSuccess">
                <!-- 搜索结果为空时 展示推荐 -->
                <div class="search-none" v-show="!productList[0]">
                    <div class="gray-bg">
                        <img src="../assets/images/sreach/none.png">
                        <div>没有找到商品，换个词搜索吧</div>
                    </div>
                    <div class="title-bg"><img src="../assets/images/sreach/recommend.png"></div>
                    <div class="search-recommend-list">
                        <SearchRecommendItem v-for="(r,i) in recommendList" :recommendList="r" :key="i" />
                    </div>
                </div>

                <!-- 搜索结果 筛选列表 -->
                <div class="result-class" v-show="productList[0]">
                    <div class="result-class-list">
                        <div class="result-class-item" :class="{active: r.checked}" v-for="(r, index) in resultList.classes" :key="index" @click="toggleClassName(resultList.classes, index)">
                            <img :src="r.class_icon">
                            <div>{{ r.class_name }}</div>
                        </div>
                    </div>
                </div>

                <!-- 搜索结果 产品列表 -->
                <div class="result-list" v-show="productList[0]">
                    <!-- 有搜索结果时 -->
                    <SearchResultItem v-for="(re, index) in productList" :reList="re.body" :key="index" v-show="re.body.class_parameters"/>

                    <!-- 当搜索结果过少时，展示推荐 -->
                    <div class="title-bg"><img src="../assets/images/sreach/recommend.png"></div>
                    <div class="search-recommend-list">
                        <SearchRecommendItem v-for="(r,i) in recommendList" :recommendList="r" :key="i" />
                    </div>
                </div>
            </div>

        </div>

    </div>
</template>
  
<script>
    import { areaList } from '@vant/area-data'
    import { Toast } from 'vant'
    import SearchResultItem from '@/components/Search/SearchResultItem.vue'
    import SearchRecommendItem from '@/components/Search/SearchRecommendItem.vue'
    export default {
    components: { SearchResultItem, SearchRecommendItem },
    data(){
        return{
            requestSuccess: false,
            discoverList: [],
            searchHistory: [],
            suggestList: [],
            resultList: [],
            productList: [],
            recommendList:[],
            values: '',
            showSearchResult: false,
            resultActive: 0,
            showRank: false,
            showFilter: false,
            rank: 0,
            rankList: ["综合排序", "新品优先"],
            priceOrder: '',
            mainSort: 0,
            filterTag: 0,
            classParameters: {},
            showShorter: true,
            showParameters: false,
            classesNum:0,
            areaList ,
            showarea:false,
            cityvalue:110102,
        }
    },
    computed: {
        showSuggest() {
            return this.values.trim() && !this.showSearchResult
        },
        showRankTxt(){
            return String(this.rankList[this.rank]).slice(0,2)
        }
    },
    methods:{
        // 搜索发现
        async getHotSList() {
            let { data } = await this.$http(`https://apis.netstart.cn/xmsc/hisearch/se_default`)
            this.discoverList = data.data.discover_list
        },

        // 搜索建议
        async getSuggestList() {
            let str = this.values.trim()
            if (!str) {
                return
            }
            let { data } = await this.$http(`https://apis.netstart.cn/xmsc/hisearch/suggestion_v3?query=${str}`)
            this.suggestList = data.data.list
        },

        // 搜索关键字的请求
        async showSearchResultHandle() {
            this.resultActive = 0
            this.rank = 0
            this.showRank = false
            this.priceOrder = ''
            this.resultList = []
            this.productList = []
            if(this.values.trim()){
                this.showSearchResult = true
                let { data } = await this.$http(`https://apis.netstart.cn/xmsc/hisearch/query_v3?query=${this.values}&page_index=1&page_size=20&main_sort=0&activity_id&activity_type&filter_tag=0`)
                this.resultList = data.data
                this.productList = this.resultList.list_v2
                // console.log(this.resultList);
                this.requestSuccess = true
            }
        },

        // 更换排序的请求
        async showSearchResultRank(mainSort = this.mainSort,classParameters = this.classParameters, filtertag = this.filterTag) {
            this.resultList = []
            this.productList = []
            if(this.values.trim()){
                this.showSearchResult = true
                let { data } = await this.$http(`https://apis.netstart.cn/xmsc/hisearch/query_v3?query=${this.values}&page_index=1&page_size=20&main_sort=${mainSort}&activity_id&activity_type&class_parameters=${classParameters}&filter_tag=${filtertag}`)
                this.resultList = data.data
                this.productList = this.resultList.list_v2
                // console.log(this.productList);
                this.requestSuccess = true
            }
        },

        // 推荐列表
        async getRecommendList() {
            let { data } = await this.$http("https://apis.netstart.cn/xmsc/home/recommendBlank")
            this.recommendList = data.data.recom_list
            // console.log(this.recommendList);
        },

        // 输入框获取光标
        searchFocusHandle() {
            if (this.showSearchResult) {
                this.getSuggestList()
                this.showSearchResult = false
            }
        },

        // 历史记录
        getSearchHistory() {
            this.searchHistory = JSON.parse(localStorage.searchHistory || '[]')
        },

        // 将历史记录存入本地
        searchKeyWord(kw) {
            this.requestSuccess = false
            this.values = kw.trim()
            if(this.values){
                let searchHistory = JSON.parse(localStorage.searchHistory || '[]')
                searchHistory = [this.values, ...searchHistory.filter(k => k !== this.values)]
                this.searchHistory = searchHistory
                localStorage.searchHistory = JSON.stringify(searchHistory)
                this.showSearchResultHandle()
            }else{
                Toast({
                    message: '搜索不能为空',
                });
            }
        },

        // 清除本地历史记录
        removeSearchHistory() {
            let searchHistory = JSON.parse(localStorage.searchHistory)
            searchHistory = []
            this.searchHistory = []
            localStorage.searchHistory = JSON.stringify(searchHistory)
        },

        // 切换搜索结果的nav
        toggleResultNav(n) {
            if(n === this.resultActive && this.resultActive === 2){
                if(this.priceOrder == 'asc'){
                    this.priceOrder = 'dsc'
                    this.productList = this.productList.sort(function(a,b){
                        return b.body.market_price - a.body.market_price
                    })
                }else {
                    this.priceOrder = 'asc'
                    this.productList = this.productList.sort(function(a,b){
                        return a.body.market_price - b.body.market_price
                    })
                }
            }else{
                this.resultActive = n
                
                if(this.resultActive === 0){
                    this.showRank = !this.showRank
                }
                
                if(this.resultActive === 1){
                    this.mainSort = 1
                    this.requestSuccess = false
                    this.showSearchResultRank(this.mainSort, this.classParameters, this.filterTag)
                }

                if(this.resultActive === 2){
                    this.priceOrder = 'asc'
                    this.productList = this.productList.sort(function(a,b){
                        return a.body.market_price - b.body.market_price
                    })
                }
            }
        },

        // 弹窗
        toggleShowRank(n){
            this.rank = n
            if(this.rank === 0){
                this.mainSort = 0
            }
            if(this.rank === 1){
                this.mainSort = 4
            }
            this.showRank = false
            this.requestSuccess = false
            this.showSearchResultRank(this.mainSort, this.classParameters, this.filterTag)
        },

        // 展开分类按钮
        shorter(){
            this.showShorter = !this.showShorter
        },

        // 切换选中状态
        toggleFilter(arr, index) {
            arr[index].checked = !arr[index].checked
        },

        toggleFilterTab(arr, index) {
            if( index !== this.classesNum || !this.showParameters ) {
                for(let a = 0; a < arr.length; a++){
                    arr[a].checked = false
                }
                arr[index].checked = true
                this.classesNum = index
            }
            this.showParameters = true
        },
        
        toggleClassName(arr, index){
            this.requestSuccess = false
            this.toggleFilterTab(arr, index)
            let parameterList = {
                "class_name": arr[index].class_name,
                "class_parameters": []
            }

            this.classParameters = JSON.stringify(parameterList)
            // 分类请求
            this.showSearchResultRank(this.mainSort, this.classParameters, this.filterTag)
        },

        // 重置按钮
        resetBtn() {
            let arrList = [ this.resultList.filter_tags, this.resultList.classes ]
            for(let a = 0; a < arrList.length; a++){
                for(let b = 0; b < arrList[a].length; b++){
                    arrList[a][b].checked = false
                }
            }

            // resultList.classes[classesNum].class_parameters[i].rules
            let arr = this.resultList.classes
            for(let i = 0; i < arr.length; i++){
                for(let j = 0; j < arr[i].class_parameters.length; j++){
                    for(let k = 0; k < arr[i].class_parameters[j].rules.length; k++){
                        arr[i].class_parameters[j].rules[k].checked = false
                    }
                }
            }
        },

        // 提交多选 请求
        submitBtn() {
            this.requestSuccess = false
            // className
            let className = []
            for(let a = 0; a < this.resultList.classes.length; a++){
                if(this.resultList.classes[a].checked){
                    className.push(this.resultList.classes[a])
                }
            }

            // class_parameters
            let parameterNameList = []
            let ruleList = []
            let arr = this.resultList.classes[this.classesNum].class_parameters
            for(let i = 0; i < arr.length; i++){
                // parameter_name
                for(let j = 0; j < arr[i].rules.length; j++){
                    if(arr[i].rules[j].checked){
                        let name = arr[i].parameter_name
                        parameterNameList = [...parameterNameList.filter(i => i !== name), name]
                    }
                }
                
                // rules
                let newArr1 = arr[i].rules.filter(i => i.checked === true )
                if(newArr1[0]){
                    ruleList.push(newArr1)
                }
            }

            // console.log(parameterNameList, ruleList);

            let classPList = []
            for(let b = 0; b < parameterNameList.length; b++ ){
                let selectRulesList = []
                for(let c = 0; c < ruleList[b].length; c++){
                    let selectRules = {
                        "name": ruleList[b][c].name
                    }
                    selectRulesList.push(selectRules)
                }

                let parameterList2 = {
                    "parameter_name": parameterNameList[b],
                    "rules": selectRulesList
                }
                classPList.push(parameterList2)

                // console.log(selectRulesList)
            }

            let parameterList = {
                "class_name": className[0].class_name,
                "class_parameters": classPList
            }

            // console.log(parameterList)

            this.classParameters = JSON.stringify(parameterList)
            // 分类请求
            this.showSearchResultRank(this.mainSort, this.classParameters, this.filterTag)

            // 隐藏筛选框
            this.showFilter = false
        },

        // 返回按钮
        returnInput() {
            if(this.values.trim()){
                this.values = ''
                this.showSearchResult = false
            }else{
                this.$router.go(-1)
            }
        },

        //显示地址
        showArea(){
            this.showarea = !this.showarea
        },
        //获取地址名称
        changeValue(a){
            this.cityvalue = a[2].code
            // console.log(a[0].name);
            let d = `${a[0].name}-${a[1].name}-${a[2].name}`
            this.$store.commit("changelocal",d)
            // console.log(this.$store.state.local);
            this.showarea = false
        }

    },
    mounted(){
        this.getHotSList()
        this.getSearchHistory()
        this.getRecommendList()
    }
  
  }
</script>
  
<style lang="scss" scoped>
  .search-view{
    padding-top: 10vw;
    .search-top{
        position: fixed;
        top: 0;
        width: 100vw;
        height: 10vw;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f2f2f2;
        padding-right: 2vw;
        box-sizing: border-box;

        img{
            width: 8vw;
            height: 8vw;
        }

        .search-input{
            input{
                width: 70vw;
                height: 7vw;
                padding: 0 3vw;
                border: none;
            }
        }
    }

    .resultbg{
        background-color: #fafafa;
    }

    .search-first{
        color: #3c3c3c;
        padding: 0 3vw;
        box-sizing: border-box;

        .search-history{
            
            .search-title{
                line-height: 10vw;
                padding-top: 4vw;
                font-size: 16px;
                font-weight: bold;
                display: flex;
                justify-content: space-between;
                align-items: center;

                img{
                    width: 4vw;
                    height: 4vw;
                }
            }

            .search-history-list{
                font-size: 14px;
                
                .search-history-item{
                    display: inline-block;
                    padding:1.5vw 4vw;
                    border-radius: 8vw;
                    background-color: #f5f5f5;
                    margin: 2vw;
                }
            }
        }

            .search-discover{

            .search-title{
                font-size: 16px;
                font-weight: bold;
                padding: 5vw 0 3vw 0;
            }

            .search-discover-list{
                padding: 0 2vw;
                box-sizing: border-box;
                display: flex;
                justify-content: space-between;
                flex-wrap: wrap;

                .search-discover-item{
                    width: 50%;
                    height: 10vw;
                    line-height: 10vw;
                }
            }
        }

    }

    .search-suggest{
        color: #333333;
        width: 100vw;
        padding: 0 4vw;
        box-sizing: border-box;

        .search-suggest-item{
            height: 12vw;
            line-height: 12vw;
            border-bottom: #d9d9d9 1px solid;
        }
    }
    
    .search-result{
        padding-top: 12vw;
        .search-result-nav{
            position: fixed;
            top: 10vw;
            display: flex;
            justify-content: space-between;
            background-color: #fafafa;

            .search-result-nav-item{
                color: #737373;
                width: 25vw;
                height: 12vw;
                line-height: 12vw;
                text-align: center;
                position: relative;

                &.active{
                    color: #ff6700;

                    .icon-down1{
                        border-top: #ff6700 6px solid;
                    }
                }

                .icon-down1{
                    width: 0;
                    height: 0;
                    position: absolute;
                    top: 50%;
                    right: 16px;
                    transform: translateY(-2px);
                    border: transparent 6px solid;
                    border-top: #737373 6px solid;
                }

                .icon-up{
                    width: 0;
                    height: 0;
                    position: absolute;
                    top: 55%;
                    right: 16px;
                    transform: translateY(-15px);
                    border: transparent 6px solid;
                    border-bottom: #737373 6px solid;
                    
                    &.active{
                        border-bottom: #ff6700 6px solid;
                    }
                }
                
                .icon-down{
                    width: 0;
                    height: 0;
                    position: absolute;
                    top: 55%;
                    right: 16px;
                    border: transparent 6px solid;
                    border-top: #737373 6px solid;

                    &.active{
                        border-top: #ff6700 6px solid;
                    }
                }
            }
        }

        .search-result-nav1{
            color: rgba(0,0,0,0.87);;
            font-size: 14px;
            width: 100vw;
            height: 28vw;
            line-height: 14vw;
            position: fixed;
            top: 22vw;
            box-sizing: border-box;
            background-color: #fff;

            .search-result-nav1-item{
                padding: 0 4vw;
                box-sizing: border-box;
            }

            .search-result-nav1-item:first-of-type{
                border-bottom: #f2f2f2 2px solid;
            }

            .search-result-nav1-item.active{
                color: #ff6700;
            }

            .fill-content{
                height: 80vh;
                background-color: rgba(0,0,0,0.5);
            }
        }
        
        .popup-list-box{
            width: 100%;
            height: 100vh;
            position: relative;
        
            .popup-list{
                width: 100%;
                height: 90vh;
                overflow: auto;
                // background-color: #f8f8f8;
                background-color: #ccc;

                .mt-4{
                    margin-top: 4vw;
                }

                .popup-item{
                    padding: 1.5vw 0;
                    box-sizing: border-box;
                    background-color: #ffffff;

                    .popup-item-title{
                        padding: 0 4vw;
                        box-sizing: border-box;
                        display: flex;
                        justify-content: space-between;
                        align-items: baseline;
                        color: #757575;

                        .span-location{
                            color: #ff6700;
                            font-size: 13px;

                            img{
                                width: auto;
                                height: 13px;
                            }
                        }
                        
                        .span-down{
                            width: 4vw;
                            height: 2.5vw;
                            background-image: url(../assets/images/sreach/down.png);
                            background-size: contain;
                            background-repeat: no-repeat;
                        }

                        .span-up{
                            width: 4vw;
                            height: 2.5vw;
                            background-image: url(../assets/images/sreach/up.png);
                            background-size: contain;
                            background-repeat: no-repeat;
                        }
                    }

                    .popup-item-con{
                        margin: 3vw 0;
                        display: flex;
                        flex-wrap: wrap;

                        &.active{
                            height: 11vw;
                            overflow: hidden;
                        }

                        div{
                            width: 24vw;
                            height: 9vw;
                            text-align: center;
                            line-height: 9vw;
                            font-size: 14px;
                            border-radius: 1vw;
                            margin:1.5vw 1.9vw;
                            background-color: #f5f5f5;
                            border: 1px solid #f5f5f5;
                            overflow: hidden;

                            &.active{
                                color: #ff6700;
                                border: 1px solid #ff6700;
                                background: #fde0d5;
                            }
                        }
                    }
                }
            }

            .submit-btn{
                width: 100%;
                position: absolute;
                left: 0;
                bottom: 0;

                button{
                    font-size: 14px;
                    width: 50%;
                    height: 14vw;
                    background-color: #ffffff;
                    border: none;

                    &:last-of-type{
                        color: #fff;
                        background-color: #ff6700;
                    }
                }
            }
        }

        .requesting{
            text-align: center;
            padding: 20vw 0;

            img{
                width: 20vw;
            }
        }
        
        .search-none{
            width: 100vw;
            
            .gray-bg{
                line-height: 7vw;
                color: #757575;
                font-size: 13px;
                padding: 7vw 0;
                box-sizing: border-box;
                background-color: #f4f4f4;
                text-align: center;
                img{
                    width: 33vw;
                }
            }

            .title-bg{
                text-align: center;

                img{
                    width: 100vw;
                }
            }

            .search-recommend-list{
                display: flex;
                justify-content: space-between;
                flex-wrap: wrap;
            }
        }

        .result-class{
            width: 100vw;
            height: 32vw;
            background-color: #f4f4f4;
            padding: 0 2vw;
            padding-top: 4vw;
            box-sizing: border-box;
            overflow: hidden;
            
            .result-class-list{
                height: 33vw;
                display: flex;
                overflow: auto;

                .result-class-item{
                    color: #3c3c3c;
                    font-size: 13px;
                    width: 20vw;
                    height: 24vw;
                    text-align: center;
                    margin-right: 2vw;
                    border-radius: 2vw;
                    background-color: #fff;

                    &.active{
                        color: #ff6700;
                    }

                    img{
                        width: 17.5vw;
                        height: 17.5vw;
                    }
                }
            }
        }
        
        .result-list{

            .title-bg{
                text-align: center;

                img{
                    width: 100vw;
                }
            }

            .search-recommend-list{
                display: flex;
                justify-content: space-between;
                flex-wrap: wrap;
            }

        }

    }
    
  }
</style>